package com.lsx143.wordcount.day10;

import com.lsx143.wordcount.bean.WaterSensor;
import com.lsx143.wordcount.day2.RandomWaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

public class Flink_GroupWindow_SQL_test {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        RandomWaterSensor randomWaterSensor = new RandomWaterSensor();
        randomWaterSensor.setSpeed(2);
        randomWaterSensor.setRun_mode(RandomWaterSensor.RUN_MODE.BY_FILE);
        SingleOutputStreamOperator<WaterSensor> dss = env
                .addSource(randomWaterSensor)
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                                .withTimestampAssigner((ws, ts) -> ws.getTs() * 1000L)
                );

        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);

        // 每隔5s统计最近5s内每个传感器的水位和
        Table table = tEnv.fromDataStream(dss, $("id"), $("ts").rowtime(), $("vc"));
        tEnv.createTemporaryView("sensor", table);

        tEnv.sqlQuery("select " +
                " id, " +
                " tumble_start(ts, interval '5' second) stt, " +
                " tumble_end(ts, interval '5' second) edt, " +
                " count(*) sensor_count, " +
                " sum(vc) sum_vc " +
                "from sensor " +
                "group by id, TUMBLE(ts, interval '5' second)")
                .execute()
                .print();
        System.out.println("-------------");
        dss.print();
        env.execute();

    }
}
